package com.milo.entity;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.StaxDriver;

/**
 * @author milogenius
 * @date 2020-04-03 20:30
 */
public class Person {
    private String firstname;
    private String lastname;
    private PhoneNumber phone;
    private PhoneNumber fax;

    public Person(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }

    //get and set methoods
    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public PhoneNumber getPhone() {
        return phone;
    }

    public void setPhone(PhoneNumber phone) {
        this.phone = phone;
    }

    public PhoneNumber getFax() {
        return fax;
    }

    public void setFax(PhoneNumber fox) {
        this.fax = fox;
    }

    @Override
    public String toString() {
        return "Person{" +
                "firstname='" + firstname + '\'' +
                ", lastname='" + lastname + '\'' +
                ", phone=" + phone +
                ", fax=" + fax +
                '}';
    }

    public static void main(String[] args) {
        /**
         * 将对象序列化为XML
         */
      // XStream xstream = new XStream();
       // XStream xStream = new XStream(new DomDriver());
       // XStream xStream = new XStream(new StaxDriver());
       // xstream.alias("person",Person.class);
       // xStream.aliasField("first",Person.class,"firstname");

/*
        Person person = new Person("Joe", "milo");
        person.setPhone(new PhoneNumber(123,"1234-456"));
        person.setFax(new PhoneNumber(123,"999-456"));

        String xml = xstream.toXML(person);
        System.out.println(xml);
*/

        /**
         * 从XML反序列化对象
         */
        XStream xstream = new XStream();
        xstream.alias("person",Person.class);
        String xmldemo = "<?xml version=\"1.0\" ?><person><firstname>Joe</firstname><lastname>milo</lastname><phone><code>123</code><number>1234-456</number></phone><fax><code>123</code><number>999-456</number></fax></person>";
        Person o = (Person)xstream.fromXML(xmldemo);
        System.out.println(o.toString());
    }
}
